<template>
  <div>
      <el-container>
        <el-header>
          <Tops></Tops>
        </el-header>
        <el-container>
          <el-aside class="aside">
            <el-tree
              :data="list"
              show-checkbox
              node-key="id"
              ref="tree"
              :default-checked-keys="[checkId]"
              highlight-current
              :props="defaultProps"
              :default-expanded-keys="[checkId]"
              class="tabp"
            >
            </el-tree>
              
              <!-- 左边树状图选择相应的楼，然后点击开始对比，表格显示相应的数据 -->
              <el-button
                type="primary"
                @click="getCheckedKeys"
                class="starts"
                icon="el-icon-pie-chart"
              >开始对比</el-button>
          </el-aside>
          <el-main>
            <div style="margin-top: 10px;">
              <el-form :inline="true">
                <el-form-item label="偏差基准值" >
                  <el-button @click="dialogFormVisible = true;" 
                  v-if="treeArred.length =='' ">{{jzname}}</el-button>
                    <el-button @click="dialogFormVisible = true;" 
                  v-else>{{jzname}}</el-button>
                </el-form-item>
                <!--  -->
                <el-form-item label="偏差值%" >
                    <el-button width="10px" @click="dialogTableVisible = true;" 
                  v-if="already =='1' ">{{num}}~{{nums}}</el-button>
                    <el-button width="10px" @click="dialogTableVisible = true;" 
                  v-else>-10~10</el-button>
                </el-form-item>
                <!-- 选择想显示的相关列 -->
                <el-form-item >
                  <el-button icon="el-icon-view"  @click="showCol">设置显示列</el-button>
                </el-form-item>
                <el-form-item >
                  <el-button icon="el-icon-download"  @click="download">下载范围外数据</el-button>
                </el-form-item>
              </el-form>
            </div>
            <el-form :model="form">
             </el-form>
             <!-- <template slot-scope="scope">
                <span                  
                  :style="((scope.row.colName && scope.row.colName[itemInd - 1])?
                  scope.row.colName[itemInd - 1][child.prop + 'Flg'] : '') == true ? 'color:red' : ''"
                 >   
                   {{scope.row.colName && scope.row.colName[itemInd - 1] ? scope.row.colName[itemInd - 1][child.prop] : ''}}</span>
              </template> -->
              <div style="height:80vh">
                <vxe-grid
                  ref="xTable"
                  border
                  resizable
                  :max-height="maxTableHeight"
                  :heigth="tableHeight"
                  :tree-config="{children: 'children',expandRowKeys: ['row_3']}"
                  :loading="loading"
                  :edit-config="{trigger: 'click', mode: 'row', showStatus: true}"
                  :columns="tableHeader"
                  @cell-click="cellClickEvent"
                  @change="rowids"
                  class="cont"
                  :cell-style="cellStyle"
                  :data="content.tableData">
                </vxe-grid>
                  <div class="detail" id="footer"  v-if="play">
                    <el-tabs :tab-position="tabPosition" @tab-click="handleClick"
                    :smallTable="tableHeights"
                    >
                    <div id="expander"></div>
                    <div class="icon-down" style="text-align:center;"><i class="el-icon-arrow-down down" style="color:#ffffff" @click="out"></i></div>
                      <el-tab-pane 
                        :name="index"
                        v-for="(item,index) in details"
                        :key="index"
                        :label="item.structureName"
                        :value="item.structureName"
                        style="overflow-y:scroll"
                      >
                        <el-tabs
                          v-model="tabCur"
                          type="card"
                        >
                        <el-tab-pane label="清单详情"  name="first">
                          <div v-html="item.particulars" style="white-space: pre-wrap;text-align:left;"></div>
                          </el-tab-pane>
                          <el-tab-pane label="清单构成" name="second">
                            <el-table
                                :data="tableData"
                                row-key="id"
                                :key="index"
                                border
                                :height="tableH"
                                id="smallTable"
                                :default-sort = "{prop: 'date', order: 'descending'}"
                                ref="filterTable"
                                :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
                            >
                            <el-table-column
                                v-for="(val,i) in item.columnName"
                                :prop="val.prop"
                                :label="val.label"
                                v-bind="setFixed(val)"
                                :key="i"
                                width="180"
                            >
                          </el-table-column>
                        </el-table>
                      </el-tab-pane>
                      </el-tabs>
                      </el-tab-pane>
                    </el-tabs>
                  </div>
              </div>
          </el-main>
        </el-container>
      </el-container>
  <!-- 弹窗设置信息 -->
    <el-dialog title="设置偏差标准" :visible.sync="dialogFormVisible">
      <el-form :model="form">
        <el-form-item label="偏差值设置" :label-width="formLabelWidth">
          <el-input-number v-model="num"  :min="-100" :max="-1">
          </el-input-number>
          ~
          <el-input-number v-model="nums" :min="0" :max="100">
          </el-input-number>
        </el-form-item>
        <el-form-item label="偏差基准" :label-width="formLabelWidth">
          <el-select v-model="jzname" placeholder="请选择" @change="changeValue($event)">
            <el-option 
             v-for="(item,id) in treeArred"
             :key="id"
             :label="item.name"
             :value="item.name"
             :value-key="item.id"
            ></el-option> 
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogFormVisible = false;getCheckedKeys()">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="设置偏差" :visible.sync="dialogTableVisible">
      <el-form :model="form">
        <el-form-item label="偏差值设置" :label-width="formLabelWidth">
          <el-input-number v-model="num"  :min="-100" :max="-1">
          </el-input-number>
          ~
          <el-input-number v-model="nums" :min="0" :max="100" >
          </el-input-number>
        </el-form-item>
        <el-form-item label="偏差基准" :label-width="formLabelWidth">
          <el-select v-model="jzname" placeholder="请选择"  @change="changeValue($event)">
            <el-option 
             v-for="(item,id) in treeArred"
             :key="id"
             :label="item.name"
             :value="item.name"
            ></el-option> 
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogTableVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogTableVisible = false;getCheckedKeys()">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 设置显示列 -->
    <el-dialog title="请勾选需要显示的列" :visible.sync="dialogTableVisibleshow">
      <el-form :model="form">
          <div style="margin: 15px 0;"></div>
          <el-checkbox-group v-model="tcolums" @change="onChangeCol">
            <el-checkbox 
            checked
            v-for="(item, itemInd) in tcolum"
            :prop="item.prop"
            :key="itemInd"
            :label="item.label"></el-checkbox>
          </el-checkbox-group>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogTableVisibleshow = false">取 消</el-button>
        <!-- <el-button type="primary" :disabled="diss"  @click="dialogTableVisibleshow = false;sures()">确 定</el-button> -->
        <el-button type="primary" :disabled="diss"  
          @click="dialogTableVisibleshow = false;changeSure()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import Tops from "../components/Top";
import {Loading} from 'element-ui'
import $ from 'jquery'
import fileDownload from 'js-file-download'
export default {
  inject:['reload'],
  data() {
    return {
      tableColumn: [
        // { field: 'name', title: '项目', width: 200,fixed:'left',treeNode: true },
      ],
       tableProxy: {
          ajax: {
            // 处理树结构转换
            query: () => XEAjax.post('/SingleCompare').then(
              data => 
                XEUtils.toArrayTree(
                data.tableData, 
                { key: 'id', parentKey: 'parentid',children: 'children' }
              )
              )
          }
        },
      search: "",
      content: {},
      contentss: {},
      tcolum:[],
      loading: true,
      fixeds:['name'],
      isIndeterminate: true,
      citys: [],
      user: '',
      list: [],
      checkId:[],
      defaultProps: {
        children: "children",
        label: "name"
      },
      activeName: "first",
      play: false,
      tableHeight: '',
      tableHeights: '',
      maxTableHeight:'',
      tableH:'',
      treeArr: [],
      details: {},
      tabCur: "first",
      dialogTableVisible: false,
      dialogFormVisible: false,
      dialogTableVisibleshow:false,
      form: {
        name: '',
        region: '',
        date1: '',
        date2: '',
        delivery: false,
        type: [],
        resource: '',
        desc: ''
      },
      formLabelWidth: '120px',
      num: '',
      nums:'',
      treeArred:[],
      jzname:'',
      tcolums:[],
      checkC:[],
      checkClum:[],
      tabPosition: 'left',
      expends:[],
      isReloadData:true,
      sele:[],
      tsd:'',
      jznameid:'',
      diss:false,
      childTime:new Date().getTime(),
      fileId:'',
      columns: [],
      initColumns:7,
      changeVa:[],
      valsLen:'',
      already:'',
      showDetails: false,
      selectTab: 'tab1',
    };
  },   
  computed:{
    tableHeader(){
      let columns = this.content.columnName;
      let config =[
         { field: 'name', title: '项目', width: 300,fixed:'left',treeNode: true },
      ]
      for(let item in columns){
        if(columns[item].prop!='name'){
          let lists = {
            field:columns[item].prop,
            title:columns[item].label,
            children:[],
          }
          let itemChildren = columns[item].children;
          let dicts=null
          for(let child in itemChildren){
            // console.log(itemChildren[child].prop)
            dicts = { field: 'colName['+(item-1)+']'+'.'+itemChildren[child].prop, 
                      title: itemChildren[child].label,width:130   
                    }
            lists.children.push(dicts)
          }
         config.push(lists)
        }
      }
      return config
    }
  },
  created () {
    // let that = this
    // let heightStyle = that.$refs.tableCot.offsetHeight
    // console.log(heightStyle)
    // that.tableHeight = heightStyle
  },
  methods: {
     cellStyle ({ row, rowIndex, column, columnIndex }) {
      // console.log(row);
      let cols = row.colName
      for(let item in cols){
        if (column.property == 'colName['+item+'].amount') {
          if (cols[item].amountFlg) {
            return {
              color: '#ff0000'
            }
          }
        }else if (column.property == 'colName['+item+'].constrscale') {
          if (cols[item].constrscaleFlg) {
            return {
              color: '#ff0000'
            }
          }
        }else if (column.property == 'colName['+item+'].price') {
          if (cols[item].priceFlg) {
            return {
              color: '#ff0000'
            }
          }
        }else if (column.property == 'colName['+item+'].quantity') {
          if (cols[item].quantityFlg) {
            return {
              color: '#ff0000'
            }
          }
        }else if (column.property == 'colName['+item+'].unitcontent') {
          if (cols[item].unitcontentFlg) {
            return {
              color: '#ff0000'
            }
          }
        }else if (column.property == 'colName['+item+'].unitcost') {
          if (cols[item].unitcostFlg) {
            return {
              color: '#ff0000'
            }
          }
        }
      }
      
    },
    rowids(column){
      console.log(column);
    },
    onChangeCol(val){
      let values = ["项目",...val]
      this.changeVa = values;
      let valsLen = values.length;
      // console.log(valsLen)
      if(valsLen<2){
         this.$alert("最少需要显示一项内容", "提示", {
          confirmButtonText: "确定",
        });
        this.diss = true;
        return false;
      }else{
        this.diss = false;
      }
    },
    changeSure(){
      let vals = this.changeVa;
      this.$refs.xTable.resetColumn()
      this.columns = this.$refs.xTable.getColumns()
      // console.log("这是什么",vals);
      this.columns.forEach(column => {
                if (!vals.includes(column.title)) {
              
                  column.visible = false
                }else{
                   column.visible = true
                }
              })
       this.$refs.xTable.refreshColumn()
    },
    cellClickEvent (column) {
      let ids = localStorage.getItem("pId");
      if(!column.row.children.length){

        this.play = true;
        this.tableHeight = 240;
        this.maxTableHeight = 240;
        this.tableHeights = 450;
        this.tableH = 430;
        let treeArr = this.$refs.tree.getCheckedKeys();
      
        let id = column.row.id;
        this.axios.post("/SingleCompareConstitute", {
            projId: ids,
            rowId: id,
            rowName: name,
            structureIdList: treeArr
          }).then(body => {
            this.details = body.data.data;
            // console.log(this.details);
            this.tableData = this.details[0].detailData
          });
      }
    },
    showCol(){
      this.dialogTableVisibleshow = true      
    },

 
    handleClick(tab) {
      // 第一次的时候  获取到第0个数据的detailData赋值给tableData
      this.tableData = this.details[tab.index].detailData
      // this.details[tab.index].particulars = this.details[tab.index].particulars.replace("\n",'<br>')
      // console.log(this.details[tab.index].particulars);
    },
    handleCheckedCitiesChange(value) {
      for(let item of value){
          this.columns.forEach(column => {
                if (item.includes(column.title)) {
                  column.visible = true
                }
              })
              
      }
       this.$refs.xTable.refreshColumn()
      if(value.length<1){
         this.$alert("最少需要显示一项内容", "提示", {
          confirmButtonText: "确定",
        });
        this.diss = true;
        return false;
      }else{
        this.diss = false;
        this.checkC = value;
      }
    },
    changeValue(value){
      console.log(123123999990)
      var obj = {};
      //使用find()方法在下拉数据中根据value绑定的数据查找对象。
      obj = this.treeArred.find(function(item){
        return item.name === value;
      })
      this.jznameid = obj.id;
    },
    sures(){
      this.loading = true
      // 将指定列设置为隐藏状态
      this.columns.forEach(column => {
        // console.log(column.property);
        if (['name'].includes(column.property)) {
          column.visible = false
        }
      })
      if (this.$refs.xTable) {
        this.$refs.xTable.refreshColumn()
      }
      this.loading = false
    },
    
    download(){
      let deviationSrc = this.num;
      let deviationDst = this.nums;
      let deviationDatum = this.jznameid;
      let treeArr = this.$refs.tree.getCheckedKeys();
      // console.log(treeArr);
      // return false;
      let id = localStorage.getItem("pId");
      this.axios({
        method:'post',
        url:'/DownloadFileCheck',
        data:{
          projId: id,
          partList: treeArr,
          deviationDatum:deviationDatum,
          deviationSrc:deviationSrc,
          deviationDst:deviationDst
        },
      
      }).then(res=>{
        if(!res.data.data){
          this.$message.error(res.data.msg)
          return false;
        }
        this.fileId = res.data.data.fileId;
          this.axios({
          method:'get',
          url:'/DownloadSingleFile',
          params:{
            projId:id,
            fileId:this.fileId
          },
          headers: {
            'Accept': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
          },
          responseType:'blob'
        }).then(list=>{
          // let blob = new Blob([res], 
          // { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
          let now = new Date();
          let date = now.getFullYear() + '-' + (now.getMonth() +1) + '-' + now.getDate();
          let exportFileName = date + ' ' + ".xlsx";
          fileDownload(list.data, exportFileName);
          // this.fileId = res.data.fileId;
          // console.log(list);
          
        })
      })
    },
    out() {
      this.play = false;
      this.tableHeight = 750;
      this.maxTableHeight = 750;
      this.tableHeights = 0;
      this.tableH = 0;
    },
    getCheckedKeys() {
      this.already = 1;
      let deviationSrc = this.num;
      let deviationDst = this.nums;
      let deviationDatum = this.jznameid;
      let treeArr = this.$refs.tree.getCheckedKeys();
      let treeArrs = this.$refs.tree.getCheckedNodes();

      if(treeArrs.length == 0){
        this.$alert("不能为空，请选择至少一项内容", "提示", {
          confirmButtonText: "确定",
        });
        return false;
      }else{
          let treeArre = [];
      let treeArrary = [];
      let ts = [];
      let ads = [];
      for(var i=0;i<treeArrs.length;i++){
        if(treeArrs[i].children!=undefined){
            treeArre.push({id:treeArrs[i].id, name:treeArrs[i].name});
        }
      }
      this.checkId = treeArre;
      let id = localStorage.getItem("pId");
      this.loading=true;
      this.$http.post("/GetLeftTree", {
            projId: id
          }).then(result => {
            this.data = result.data;
            if (this.data.status == "200") {
              ads = this.data.data;
              this.tsd = ads[0].id;
              ts.push({id:'average', name:'平均值'})
              for(var j=0;j<treeArre.length;j++){
                if(treeArre[j].id != this.tsd){
                  ts.push({id:treeArre[j].id, name:treeArre[j].name})
                }
              }
              this.treeArred = ts;
            }
          });
      this.axios.post("/SingleCompare", {
          projId:localStorage.getItem("pId"),
          deviationSrc : this.num,
          deviationDst : this.nums,
          deviationDatum : this.jznameid,
          partList : this.$refs.tree.getCheckedKeys()
        }).then(body => {
          this.content = body.data.data;
          this.isReloadData = false;
          this.$nextTick(()=>{
            this.isReloadData = true;
          })
          this.loading=false;
        });
          this.play = false;
          this.maxTableHeight = 700;
          
      }
      
    },
    open(){
        dialogFormVisible = true;
    },
    setFixed(item){
      const fixedArr = ['name'];
      return fixedArr.includes(item.prop)?{fixed:'left'}:'';
    },
  },

  components: {
    Tops,
  },
  watch:{
  
  },
  mounted() {
    this.jznameid = 'average';
    this.jzname = '平均值';
    this.num = -10;
    this.nums = 10;
    let deviationSrc = this.num;
    let deviationDst = this.nums;
    let deviationDatum = this.jznameid;
    let id = localStorage.getItem("pId");
    this.tableHeight = 750;
    this.tableHeights = 0;
    this.maxTableHeight = 750;
    this.tableH = 0;
    this.loading=true;
    this.axios
      .post("/SingleCompare", {
        projId: id,
        partList: this.treeArr,
        deviationDatum:deviationDatum,
        deviationSrc:deviationSrc,
        deviationDst:deviationDst
      })
      .then(body => {
        this.content = body.data.data;

        this.loading=false;
        this.$http
          .post("/GetLeftTree", {
            projId: id
          })
          .then(result => {
            this.data = result.data;
            if (this.data.status == "200") {
              this.list = this.data.data;
              this.checkId = this.list[0].id;
              let trees = [];
              trees.push({id:'1', name:'平均值'})
              for(var i=0;i<this.list[0].children.length;i++){
                  trees.push({id:this.list[0].children[i].id, name:this.list[0].children[i].name})
              }
              this.treeArred = trees;
            }
          });
      });

      this.$http.post("/SingleTableColumns",{

      }).then(result=>{
        this.tcolum = result.data.data;
        sessionStorage.setItem('myCloums',JSON.stringify(this.tcolum))
         this.tcolumss = sessionStorage.getItem("myCloums");
          let tc = JSON.parse(this.tcolumss);
          this.checkClum  = [];
          for (var i=0;i<tc.length;i++)
          { 
              this.checkClum.push(tc[i].label);
          }
      }),
              // this.reload();
    $(function(){
      var src_posi_Y = 0, dest_posi_Y = 0, move_Y = 0, is_mouse_down = false, destHeight = 20;

      $(document).on('mousedown','#expander',function(e){
          src_posi_Y = e.pageY;
          is_mouse_down = true;
      });
      $(document).bind("click mouseup",function(e){
          if(is_mouse_down){
            is_mouse_down = false;
          }
      }).mousemove(function(e){
          dest_posi_Y = e.pageY;
          move_Y = src_posi_Y - dest_posi_Y;
          src_posi_Y = dest_posi_Y;
          destHeight = $("#footer").height() + move_Y;
          if(is_mouse_down){
              if(destHeight<=520){
                destHeight =520; 
              }
              if(destHeight>=700){
                destHeight = 700;
              }
            this.tableHeights = destHeight;
            // $("#bigTable").css("max-height", 580-this.tableHeights);
            $("#footer").css("height", destHeight);
            $("#smallTable").css("height", destHeight-100);
          }
      }); 
  });
    
  },
  startLoading: function() {
      loading = Loading.service({
          lock: true,
          text: '加载中……',
          background: 'rgba(1, 1, 1, 0.7)'
      })
    },
  endLoading: function() {
      loading.close();      
  },
};
</script>
<style lang="stylus" scoped>
.starts {
  position: fixed;
  left: 4rem;
  height: 50px;
  width: 8rem;
  font-size: 1rem;
  bottom:0;
}
.aside{
  height:82vh;
  margin-top:2vh;
  width:30vw;
  border-right:2px solid #ccc;
  border-bottom:2px solid #ccc;
}
.tabp{
  display: inline-block;
  overflow:auto !important
}
.cont:hover {
  cursor: pointer;
}

.down {
  color: #409EFF;
  font-size: 1.5rem;
}
.down:hover {
  cursor: pointer;
}
.icon-down{
  width:50px;
  height:20px;
  background-color:#409EFF;
  margin:0 auto;
  border-radius :5px;
}
#footer {position:fixed;bottom:0;left:16%;width:83vw;z-index:1000; height:55vh; background-color:#ffffff;overflow:hidden;}
#expander{position:fixed;left:16%;width:83vw; height:6px; background-color:#999;z-index:999;}
#expander:hover{ cursor:n-resize;}
</style>